package com.xy_pro.xymanager.service;

import com.xy_pro.xymanager.entity.UserEntity;
import com.xy_pro.xymanager.exception.PasswordMismatchException;
import com.xy_pro.xymanager.exception.PasswordNotModifiedException;
import com.xy_pro.xymanager.exception.UserInfoInValidateException;
import com.xy_pro.xymanager.helper.XYUtils;
import com.xy_pro.xymanager.repository.UserRepository;
import io.micrometer.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PagedModel;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    private Logger logger = LoggerFactory.getLogger(UserService.class);

    private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();


    @PreAuthorize("hasRole('ADMIN')")  // 确保只有管理员可以调用此方法
    public UserEntity saveUser(UserEntity userInput) {
        if(userInput.getName() == null || userInput.getName().isEmpty()){
            System.out.println("用户名为空！");
            throw new UserInfoInValidateException("用户名为空");
        }
        if(userInput.getPhone() == null || userInput.getPhone().isEmpty()){
            System.out.println("用户电话号码为空！");
            throw new UserInfoInValidateException("电话号码为空");
        }
        boolean nameExist = userRepository.existsUserByName(userInput.getName());
        if(nameExist){
            System.out.println("用户名重复");
            throw new UserInfoInValidateException(userInput.getName() + " 已存在");
        }

        boolean phoneExist = userRepository.existsUserByPhone(userInput.getPhone());
        if(phoneExist){
            System.out.println("手机号码重复");
            throw new UserInfoInValidateException(userInput.getPhone() + " 已存在");
        }

        String encodedPassword = passwordEncoder.encode(XYUtils.PASSWORD_RESET);
        if(userInput.getRole() == UserEntity.Role.ROLE_ADMIN){
            encodedPassword = passwordEncoder.encode(userInput.getPhone());
        }
//        String encodedPassword = passwordEncoder.encode(XYUtils.PASSWORD_RESET);
        // 使用 builder 合并默认值和输入值
        UserEntity userToSave = UserEntity.builder()
                .name(userInput.getName())
                .password(encodedPassword)
                .phone(userInput.getPhone())
                .sex(userInput.getSex())
                .age(userInput.getAge())
                .role(userInput.getRole() != null ? userInput.getRole() : UserEntity.Role.ROLE_USER)
                .registerDate(userInput.getRegisterDate() != null ? userInput.getRegisterDate() : new Date())
                .build();

        return userRepository.save(userToSave);
    }


    public void modifyPassword(UserEntity user, String oldPassword, String newPassword) {
        // 1. 验证输入参数
        validatePasswordParams(oldPassword, newPassword);

        // 3. 验证原密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            throw new PasswordMismatchException("原密码错误");
        }


        // 5. 检查新密码是否与原密码相同
        if (passwordEncoder.matches(newPassword, user.getPassword())) {
            throw new PasswordNotModifiedException("新密码不能与原密码相同");
        }

        // 6. 加密新密码并更新
        String encodedPassword = passwordEncoder.encode(newPassword);
        user.setPassword(encodedPassword);
        userRepository.save(user);
    }

    /**
     * 验证密码参数
     */
    private void validatePasswordParams(String oldPassword, String newPassword) {
        if (oldPassword == null || oldPassword.trim().isEmpty()) {
            throw new IllegalArgumentException("原密码不能为空");
        }

        if (newPassword == null || newPassword.trim().isEmpty()) {
            throw new IllegalArgumentException("新密码不能为空");
        }

        if (newPassword.length() < 6 || newPassword.length() > 20) {
            throw new IllegalArgumentException("新密码长度需在6-20位之间");
        }
    }

    public Page<UserEntity> getUsers(String username, int currentPage, int pageSize) {
        Pageable pageable = PageRequest.of(currentPage - 1, pageSize);

        if (StringUtils.isNotBlank(username)) {
            // 有搜索关键词时按用户名查询
            logger.info("根据用户名查询用户列表：{}", username);
            return userRepository.findAllByNameContaining(username, pageable);
        } else {
            // 无搜索关键词时返回全部
            logger.info("查询所有用户列表");
            return userRepository.findAll(pageable);
        }

//        return userRepository.findAll(pageable);
    }
}
